package cn.itcast.factory;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Properties;

public class YamlPropertytySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        //1.创建yaml的解析工厂
        YamlPropertiesFactoryBean yml = new YamlPropertiesFactoryBean();
        //设置资源内容
        yml.setResources(resource.getResource());
        //解析成properties文件
        Properties properties = yml.getObject();
        //返回符合spring的propertysource对象

        return name != null ? new PropertiesPropertySource(name,properties)
               : new PropertiesPropertySource(resource.getResource().getFilename(),properties);
    }
}
